package com.wowangz.cms.common.utils;

import java.security.MessageDigest;

import javax.crypto.KeyGenerator;
import javax.crypto.Mac;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import com.wowangz.cms.syscore.exception.ServiceException;
import com.wowangz.cms.user.pojo.User;

/**
 * 
 * @author yoyo
 * 公共加密方法
 *
 */
public class CommonCrypto
{
	public static final int MIN_LENGTH = 6;
	private static char[] CHAR_NUM = { 
		'0', '1', '2', '3', '4', '5', '6', '7', '8', '9'}; 
	private static char[] CHAR_LOWER = { 
		'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 
		'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 
		'u', 'v', 'w', 'x', 'y', 'z', }; 
	private static char[] CHAR_UPPER = { 
		'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J',
		'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T',
		'U', 'V', 'W', 'X', 'Y', 'Z'}; 
	private static char[] CHAR_SPECIAL = { 
		//'!','@','#','$','%','^','&','*','~'
		'!','@','#','$','^','~'
		
	}; 
	
	private static final String SYSTEM_ENCODING = "UTF-8";
	
    private static String byteToHex(byte[] buffer)
    {
        StringBuffer sb = new StringBuffer(buffer.length * 3);
        for (int i = 0; i < buffer.length; i++) {
            sb.append(Character.forDigit((buffer[i] & 0xf0) >> 4, 16));
            sb.append(Character.forDigit(buffer[i] & 0x0f, 16));
        }
        return sb.toString();
    }
    
    /**
     * 取得HMAC密钥
     * @return
     * @throws ServiceException
     */
    private static String getMacKey() throws ServiceException
    {
    	String strMacKey = "";
    	try
    	{
	        KeyGenerator keyGenerator = KeyGenerator.getInstance("HmacMD5");
	        SecretKey secretKey = keyGenerator.generateKey();
	        BASE64Encoder base64 = new BASE64Encoder();
	        strMacKey  = base64.encode(secretKey.getEncoded());
    	}
		catch (Exception e) {
			e.printStackTrace();
			throw new ServiceException("取得HMAC密钥失败");
		}
		return strMacKey;
    }
    
    /**
     * MD5加密
     * @param arg0
     * @return
     * @throws ServiceException
     */
    public static String encryptMD5Encoder(String arg0) throws ServiceException 
    {
    	String strMD5Encoder = "";
    	try
    	{
            MessageDigest md5 = MessageDigest.getInstance("MD5");
            md5.update(arg0.getBytes(SYSTEM_ENCODING));
            byte[] md5Digest = md5.digest();
            strMD5Encoder = byteToHex(md5Digest);
    	}
		catch (Exception e) {
			e.printStackTrace();
			throw new ServiceException("MD5加密失败");
		}
		return strMD5Encoder;
    }
    
    /**
     * SHA加密
     * @param arg0
     * @return
     * @throws ServiceException
     */
    public static String encryptSHAEncoder(String arg0) throws ServiceException 
    {
    	String strSHAEncoder = "";
    	try
    	{
            MessageDigest sha = MessageDigest.getInstance("SHA");
            sha.update(arg0.getBytes(SYSTEM_ENCODING));
            byte[] shaDigest = sha.digest();
            strSHAEncoder = byteToHex(shaDigest);
    	}
		catch (Exception e) {
			e.printStackTrace();
			throw new ServiceException("SHA加密失败");
		}
		return strSHAEncoder;
    }
    
    /**
     * 用于明文密码SHA，SysUser密码专用
     * @param arg0
     * @return
     * @throws ServiceException
     */
    public static String encryptSHAEncoder(String password, User sysUser) throws ServiceException {
    	StringBuffer temp = new StringBuffer();
    	String strSHAEncoder = "";
    	try
    	{
    		temp.append(password);
            MessageDigest sha = MessageDigest.getInstance("SHA");
            sha.update(temp.toString().getBytes(SYSTEM_ENCODING));
            byte[] shaDigest = sha.digest();
            strSHAEncoder = byteToHex(shaDigest);
    	}
		catch (Exception e) {
			e.printStackTrace();
			throw new ServiceException("SHA加密失败");
		}
		return strSHAEncoder;
    }

    /**
     * MAC加密
     * @return
     * @throws ServiceException
     */
    public static String encryptHMACEncoder(String arg0, String key) throws ServiceException
    {
    	String strHMACEncoder = "";
    	try
    	{
	        byte[] bkey = new BASE64Decoder().decodeBuffer(key);
	        SecretKey secretKey = new SecretKeySpec(bkey, "HmacMD5");
	        Mac mac = Mac.getInstance(secretKey.getAlgorithm());
	        mac.init(secretKey);
	        strHMACEncoder = byteToHex(mac.doFinal(arg0.getBytes(SYSTEM_ENCODING)));
    	}
		catch (Exception e) {
			e.printStackTrace();
			throw new ServiceException("SHA加密失败");
		}
		return strHMACEncoder;
    }
    
    public static void main(String[] args) {
    	
       String msg = "royal";
        //和蔼可亲：e94f0bfab8c987a7437ba4e1697c1cc0
        //一鼓作气：e94f0bfab8c987a7437ba4e1697c1cc0
        //语联网（武汉）信息技术有限公司：4afea7d073863b9dbe80cfac0ba75d5a
        
        try {
            System.out.println("msg:" + msg);
            System.out.println("md5:" + CommonCrypto.encryptMD5Encoder(msg));
            System.out.println("sha:" + CommonCrypto.encryptSHAEncoder(msg));
            String strMacKey = CommonCrypto.getMacKey();
            System.out.println("mac key:" + strMacKey);
            System.out.println("mac:" + CommonCrypto.encryptHMACEncoder(msg, strMacKey));
        } catch (Exception e) {
            e.printStackTrace();
         }
        
        User sysUser = new User();
        sysUser.setUserno("CHNHO02232");
        sysUser.setInputtime(DataFormat.parseDate("2012-09-01", DataFormat.DT_YYYY_MM_DD));
        sysUser.setPwdchangedate(DataFormat.parseDate("2012-09-01", DataFormat.DT_YYYY_MM_DD));
        System.out.println("sha-password:" + CommonCrypto.encryptSHAEncoder("123456", sysUser));

        
    }
}